/*
 * Copyright 2010 Dovado FZ-LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dovado.dovadoremote;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;

public class Settings extends Activity {

	// TODO: remove this. Not supposed to be here
	SeekBar SeekBar01;

	static final String aliases = "ts aliases";

	public EditText hostInput;
	public EditText usernameInput;
	public EditText passwordInput;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);

		/*
		 * Display the wonderful logo:
		 */
		ImageView i = (ImageView) findViewById(R.id.dovadologo);
		i.setImageResource(R.drawable.logo);

		/*
		 * Create the "sync n save" button:
		 */
		View saveSyncButton = findViewById(R.id.savesyncbutton);

		/*
		 * Remove focus from text-input (stops keyboard from popping up)
		 */
		View hostLabel = findViewById(R.id.fakebutton);
		hostLabel.requestFocus();
		saveSyncButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				saveSettings();
				if (DAAPP.getHasStarted()) {
					DAAPP.setSyncOnDemand();
				}
				DAAPP.setHasStarted(true);
				finish();

			}
		});

		/*
		 * fill in the text fields:
		 */
		hostInput = (EditText) findViewById(R.id.EditText01);
		hostInput.setText(Communicator.getHost(this.getFilesDir()
				.getAbsolutePath()
				+ "/dovado_settings"));
		usernameInput = (EditText) findViewById(R.id.EditText03);
		usernameInput.setText(Communicator.getUsername(this.getFilesDir()
				.getAbsolutePath()
				+ "/dovado_settings"));
		passwordInput = (EditText) findViewById(R.id.EditText02);
		passwordInput.setText(Communicator.getPassword(this.getFilesDir()
				.getAbsolutePath()
				+ "/dovado_settings"));

		try {
			/*
			 * make password human readable when presented in the textfield:
			 */
			passwordInput.setText(URLDecoder.decode(Communicator
					.getPassword(this.getFilesDir().getAbsolutePath()
							+ "/dovado_settings"), "ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {

			System.err.println("Bad encoding on password!");
		}
	}

	/*
	 * If the user presses the 'back'-button (we can add some more functionality
	 * here
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			/*
			 * Intent i = new Intent(); i.setAction(Intent.ACTION_MAIN);
			 * i.addCategory(Intent.CATEGORY_HOME); this.startActivity(i);
			 * return true;
			 */
			if (DAAPP.getHasStarted()) {
				finish();
			}
		}
		return false;
	}

	/*
	 * Save settings to file:
	 */
	private void saveSettings() {
		Communicator.setUsername(usernameInput.getText().toString());
		Communicator.setHost(hostInput.getText().toString());
		Communicator.setPassword(passwordInput.getText().toString());

		/*
		 * Toast.makeText(getApplicationContext(), "Settings saved",
		 * Toast.LENGTH_LONG).show();
		 */
		writeFile();

	}

	private void writeFile() {
		PrintWriter pw;
		try {

			pw = new PrintWriter(new FileWriter(Communicator.getSettingsFile(),
					false));

			/*
			 * write hostname to file:
			 */
			pw.write(hostInput.getText().toString() + "\n");
			/*
			 * write password to file (must be ISO-8859-1 encoded for special
			 * characters)
			 */
			// System.err.println("about to write password <"
			// +URLEncoder.encode(passwordInput.getText().toString(),"ISO-8859-1")+"> to file");
			pw.write(URLEncoder.encode(passwordInput.getText().toString(),
					"ISO-8859-1")
					+ "\n");

			/*
			 * Write username to file:
			 */
			pw.write(usernameInput.getText().toString() + "\n");

			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
